<template>
  <el-row>
    <el-row>
      <el-col :span="24">
        <el-col :span="12">
          <el-page-header @back="goBack" :content="lookUpd"></el-page-header>
        </el-col>
        <el-col :span="10">
          <el-button type="primary" size="medium" style="float: right" @click="submitForm('form3')"
                     v-if="JSON.parse(decodeURIComponent(this.$route.query.flag))=='2'">保存
          </el-button>
        </el-col>
      </el-col>
    </el-row>
    <el-divider></el-divider>
    <el-row v-loading="saveLoading">
      <el-col :span="9">
        <el-form ref="form3" :model="form3" label-width="100px" :rules="rules">
          <el-form-item label="选题方向：" prop="type">
            <el-select v-model="form3.type" clearable placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.title"
                :value="item.id">
              </el-option>
              <!--              <el-option-->
              <!--                v-for="item in options"-->
              <!--                :key="item.label"-->
              <!--                :label="item.label"-->
              <!--                :value="item.label">-->
              <!--              </el-option>-->
            </el-select>
          </el-form-item>
          <el-form-item label="任务类型：" prop="radio">
            <el-radio-group v-model="form3.radio" @change="form3_radioClick">
              <el-radio v-for="(o,index) in form3.radioItem" :label="index" :key="index">{{o}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="提交内容：" prop="upContent">
            <el-select v-model="form3.upContent" placeholder="请选择提交内容"
                       multiple
                       filterable
                       allow-create
                       default-first-option
                       style="width: 100%">
              <el-option label="任务书" value="任务书"></el-option>
              <el-option label="课题审批表" value="课题审批表"></el-option>
              <el-option label="开题报告" value="开题报告"></el-option>
              <el-option label="工作流程图" value="工作流程图"></el-option>
              <el-option label="诚信承诺书" value="诚信承诺书"></el-option>
              <el-option label="项目源码" value="项目源码"></el-option>
              <el-option label="毕业论文" value="毕业论文"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="任务要求：" prop="comment">
            <el-input v-model="form3.comment"></el-input>
          </el-form-item>
          <el-form-item label="结束时间：" prop="date">
            <el-date-picker
              v-model="form3.date"
              type="datetime"
              @change="data_change"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间" style="width: 100%">
            </el-date-picker>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :offset="1" :span="14">
        <el-row class="uplold">
          <el-col :span="24" v-if="JSON.parse(decodeURIComponent(this.$route.query.flag))=='2'">
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="uploadUrl"
              :data="data"
              :http-request="myUpload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :before-upload="beforeUpload"
              accept=".xls,.xlsx,.png,.jpg,.jpeg,.doc,.docx,.ppt,.pptx,.rar,.zip"
              multiple
              :limit="45"
              :on-exceed="handleExceed"
              :file-list="fileList"
              :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button>
              <div slot="tip" class="el-upload__tip">上传文件类型只能是文档、图片或压缩文件!</div>
            </el-upload>
          </el-col>
          <el-col :span="24" class="row">
            <el-card class="box-card" shadow="never">
              <div v-if="imgList.length <= 0" style="text-align: center;font-size: 15px;color: #8c939d">暂无添加任何文件</div>
              <div slot="header" class="clearfix">
                <span>已传附件</span>
                <el-button style="float: right; padding: 3px 0" type="text" @click="refreshFile"
                           v-if="JSON.parse(decodeURIComponent(this.$route.query.flag))=='2'">刷新预览
                </el-button>
                <el-button style="float: right; padding: 3px 0" type="text" @click="allFileDown()"
                           v-if="JSON.parse(decodeURIComponent(this.$route.query.flag))!='2'"
                >全部下载
                </el-button>
              </div>
              <!--        图片-->
              <ul class="el-upload-list el-upload-list--picture-card">
          <span v-for="img in imgList">
            <el-tooltip
              class="item"
              effect="light"
              :hide-after="2000"
              :content="img.name"
              placement="bottom-start">
            <li tabindex="0" class="el-upload-list__item is-ready"
                v-if="img.type=='jpg'|img.type=='png'|img.type=='jpeg'">
              <img class="el-upload-list__item-thumbnail" :src="img.url">
              <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="imgCheck(img.url)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span class="el-upload-list__item-delete" @click="imgDonwload(img.url)">
                    <i class="el-icon-download"></i>
                  </span>
              </span>
            </li></el-tooltip>
          </span>
              </ul>
              <!--        文件file-->
              <span class="file_card">
            <ul class="el-upload-list el-upload-list--picture-card">
            <span v-for="img in imgList">
              <el-tooltip
                class="item"
                effect="dark"
                :hide-after="2000"
                :content="img.name"
                placement="bottom-start">
                <li tabindex="0" class="el-upload-list__item is-ready"
                    v-if="img.type=='docx'|img.type=='doc'|img.type=='xls'|img.type=='xlsx'">
                  <div class="demo-image__preview el-upload-list__item-thumbnail">
                    <el-image
                      style="width: 100px; height: 100px"
                      :src="img.fileImgUrl[0]"
                      :preview-src-list="img.fileImgUrl">
                    </el-image>
                    <span class="test" @click="fileDonwload(img.url)">
                      <i class="el-icon-download"></i>
                    </span>
                  </div>
                </li>
              </el-tooltip>
            </span>
          </ul>
          </span>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </el-row>
</template>

<script>
    export default {
        name: "TeaUpdateTask",
        data() {
            var validateUpContent = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入'));
                } else {
                    callback();
                }
            };
            var validateComment = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入'));
                } else {
                    callback();
                }
            };
            var validateType = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入'));
                } else {
                    callback();
                }
            };
            var validateDate = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入'));
                } else {
                    callback();
                }
            };
            return {
                saveLoading: false,
                form3: {
                    radioItem: ["项目开题", "中期检查", "毕业论文"],
                    radio: 0,
                    upContent: [],
                    comment: '',
                    type: "",
                    date: "",
                },
                data: {'userId': "1195187624378195968"},
                tea_id: this.UserInfo.getUserInfo().id,
                options: [
                    {
                        value: 'UI',
                        label: 'UI'
                    },
                    {
                        value: 'JAVA',
                        label: 'JAVA'
                    },
                    {
                        value: '前端',
                        label: '前端'
                    }
                ],
                fileList: [],
                uploadUrl: this.URL.api + "upload/file",//this.URL.api +
                UploadFileList: "",
                rules: {
                    upContent: [
                        {validator: validateUpContent, trigger: 'blur'}
                    ],
                    comment: [
                        {validator: validateComment, trigger: 'blur'}
                    ],
                    type: [
                        {validator: validateType, trigger: 'blur'}
                    ],
                    date: [
                        {validator: validateDate, trigger: 'blur'}
                    ],
                },
                dialogImageUrl: '',
                dialogVisible: false,
                disabled: false,
                imgList: [],
                imgList2: [
                    {"type": "img", "fileName": "sdkfsjdfk.jpg", "url": ["http://132.232.47.31:8080/image/w1.jpg"]},
                    {
                        "type": "file",
                        "url": ["http://132.232.47.31:8080/image/w1.jpg", "http://132.232.47.31:8080/image/w2.jpg"]
                    },
                    {"type": "img", "url": ["http://132.232.47.31:8080/image/w1.jpg"]},
                    {
                        "type": "file",
                        "url": ["http://132.232.47.31:8080/image/w1.jpg", "http://132.232.47.31:8080/image/w2.jpg"]
                    }
                ],
                LookFlag: "add",
                listType: [
                    'xls',
                    'xlsx',
                    'png',
                    'jpg',
                    'jpeg',
                    'doc',
                    'docx',
                    'ppt',
                    'pptx',
                    'rar',
                    'zip',
                ],
                lookUpd:""+JSON.parse(decodeURIComponent(this.$route.query.flag))=='2'?"编辑任务":"查看任务",
            }
        },
        methods: {
            deleteFile(url, id) {
                this.$http.post(this.URL.api + 'upload/deleteFile',
                    this.qs.stringify({fileurl: url}))
                    .then(re => {
                        this.selAllFileImg();
                        //this.UploadFileList=this.UploadFileList.replace(new RegExp(";"+id,'g'),'');
                    });
            },
            handleRemove(file, fileList) {
                if (file.response == undefined) {
                    //console.log(file.fileId)
                    this.deleteFile(file.url, file.fileId)
                } else {
                    //console.log(file.response.data.id)
                    this.deleteFile(file.response.data.url, file.response.data.id)
                }
            },
            handlePreview(file) {
                console.log(file);
            },
            form3_radioClick(e) {
                console.log(e)
            },
            submitUpload() {
                this.$refs.upload.submit();
            },
            goBack() {
                console.log('go back');
                this.$router.push({name: 'addTopic', params: {act: "3"}});
            },
            data_change(e) {
                console.log(e)
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        var self = this;
                        self.saveLoading = true;
                        // ask: "撒发射点发11111111"
                        // content: "课题审批表, 工作流程图"
                        // enclosure: null
                        // id: "1196429785207689216"
                        // releaseDate: "2019-11-18T14:07:44.041+0000"
                        // state: "0"
                        // stopDate: "2019-11-16 00:00:00"
                        // teaId: "1195999384156823552"
                        // topic: Object
                        // topicId: "1196373993722761216"
                        // type: "中期检查"
                        console.log(this.form3.type)
                        console.log(this.form3.radioItem[this.form3.radio])
                        console.log(this.form3.upContent)
                        console.log(this.form3.comment)
                        console.log(this.form3.date)
                        console.log(this.imgList)
                        var sufile = [];
                        this.imgList.forEach(re => {
                            sufile.push(re.fileId)
                        });
                        console.log(sufile)

                        var body = {
                            TopicId: this.form3.type,
                            TaskType: this.form3.radioItem[this.form3.radio],
                            submitContent: this.form3.upContent,
                            TaskRequest: this.form3.comment,
                            endTime: this.form3.date,
                            submitFile: sufile,
                            tea_id: this.tea_id,
                            taskId: JSON.parse(decodeURIComponent(this.$route.query.data2)).task.id,
                        };
                        self.$http.post(self.URL.api + "teacherAddTask/update", self.qs.stringify(body))
                            .then(function (response) {
                                console.log(response)
                                if (response.data.flag) {
                                    self.saveLoading = false;
                                    self.MyMessage("添加成功！！！", "success");
                                    self.$router.push({name: 'addTopic', params: {act: "3"}});
                                } else {
                                    self.saveLoading = false;
                                    self.MyMessage("添加失败，请稍后再试！", "warning");
                                }
                            })
                            .catch(function (error) {
                                self.saveLoading = false;
                                console.log(error)
                                self.MyMessage("添加失败，请稍后再试！", "warning");
                            });
                    } else {
                        return false;
                    }
                });
            },
            uploadSuccess(response, file, fileList) {
                if (file.response.flag) {
                    this.selAllFileImg()
                    //this.UploadFileList = this.UploadFileList + ";" + file.response.data.id
                }
            },
            uploadError(err, file, fileList) {
                //console.log(err)
                console.log("失败")
            },
            beforeUpload(file) {
                console.log(file)
                var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
                var extension1 = false;
                this.listType.forEach(re => {
                    if (testmsg == re)
                        extension1 = true;
                })
                if (!extension1) {
                    this.$message({
                        message: '上传文件类型只能是文档、图片或压缩文件!',
                        type: 'warning'
                    });
                }
                return extension1;
            },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 15 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            imgDonwload: function (img) {
                console.log("imgDonwload:" + img);
                window.location.href = this.URL.api + "upload/testDownload?file=" + img;
            },
            imgCheck(img) {
                console.log("imgCheck:" + img)
                this.dialogImageUrl = img;
                this.dialogVisible = true;
            },
            fileDonwload(img) {
                console.log("fileDonwload:" + img)
                window.location.href = img;
            },
            myUpload(content) {
                console.dir(content)
                let formData = new FormData();
                formData.append('file', content.file);
                formData.append('userId', this.tea_id);
                this.$http.post(content.action, formData, {
                    headers: {
                        "Content-Type": "multipart/form-data"
                    },
                    onUploadProgress: progressEvent => {
                        let percent = (progressEvent.loaded / progressEvent.total * 99) | 0
                        content.onProgress({percent: percent})
                    }
                }).then((res) => {
                    if (res.data.flag) {
                        content.onSuccess(res.data)
                    } else {
                        content.onError(res.data)
                    }
                }).catch((err) => {
                    content.onError()
                });
            },
            selAllFileImg: function () {
                var self = this;
                self.$http.post(self.URL.api + "upload/selAllFileUrlByUserId", self.qs.stringify({
                    userId: this.tea_id,
                    taskId: self.LookFlag
                }))
                    .then(function (response) {
                        console.log(response)
                        self.imgList = response.data.data
                    })
                    .catch(function (error) {
                    });
            },
            MyMessage(msg, type) {
                this.$message({
                    message: msg,
                    type: type
                });
            },
            refreshFile() {
                this.selAllFileImg();
            },
            LookData(data) {
                var content1 = data.task.content.split(',');
                content1.forEach(re => {
                    this.form3.upContent.push(re)
                })
                console.log(data.task)
                console.log(this.options)
                this.form3.radio = this.form3.radioItem.indexOf(data.task.type);
                this.form3.comment = data.task.ask
                this.form3.type = data.task.topicId;
                this.form3.date = data.task.stopDate;
                this.imgList = data.file
                this.fileList = data.file
            },
            allFileDown() {
                window.location.href = this.URL.api + "upload/Downloadbatch/" + this.tea_id + "/" + this.LookFlag + "/任务附件"
            },
        },
        mounted: function () { // mounted　表示这个 Vue 对象加载成功了
            var self = this;
            self.$http.post(self.URL.api + 'teacherTopic/select', self.qs.stringify({
                str: null,
                status: "1",
                teaId: self.UserInfo.getUserInfo().id
            }))
                .then(function (response) {
                    self.options = response.data.data;
                    console.log("加载11111", self.options)
                    JSON.parse(decodeURIComponent(self.$route.query.data2))
                    let data = JSON.parse(decodeURIComponent(self.$route.query.data2));
                    console.log(data)
                    if (data != undefined) {
                        self.LookData(data);
                        self.LookFlag = data.task.id;
                    } else {
                        self.LookFlag = "add";
                        self.goBack();
                    }
                }).catch(function (error) {
                console.log("加载失败！！！", error)
            });
        }
    }
</script>

<style scoped>

  .row >>> .el-divider--horizontal {
    margin: 10px 0;
  }

  .row >>> .el-card__header {
    padding: 8px 24px;
  }

  .row >>> .el-card {
    margin-top: 15px;
  }

  .row >>> .el-upload-list__item {
    width: 100px;
    height: 100px;
  }

  .row >>> .el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }

  .uplold >>> .el-upload-list__item {
    transition: none;
  }

  .file_card >>> .el-upload-list__item-actions {
    height: 20%;
    font-size: 10px;
  }

  .file_card >>> .el-upload-list__item-thumbnail:hover .test {
    opacity: 1;
  }

  .test {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 20px;
    background: rgba(0, 0, 0, 0.5);
    color: #ffffff;
    opacity: 0;
    text-align: center;
    cursor: pointer;
    font-size: 16px;
    line-height: 20px;
  }

  .content {
    position: absolute;
    bottom: -30px;
    left: 0;
    width: 100%;
    height: 30px;
    background: rgba(0, 0, 0, 0.5);
    color: #ffffff;
    text-align: center;
    cursor: pointer;
    font-size: 16px;
    z-index: 9999;
  }

</style>
